package com.toptower.rfid_read_write.util;

import android.os.Environment;

import android.util.Log;


import com.toptower.rfid_read_write.model.SingleBaseConfig;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * author : shangrong
 * date : 2019/5/23 11:46 AM
 * description :对配置文件进行读取和修改
 */
public class ConfigUtils {

    // 配置文件路径
    public static final String filePath = Environment.getExternalStorageDirectory() + File.separator + "RfidReadOrWriteConfig.txt";


    public static boolean isConfigExit() {
        File file = new File(filePath);
        if (file.exists()) {
            return true;
        } else {
            try {
                file.createNewFile();
                modityJson();
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
            return true;
        }
    }


    /**
     * 判断SDCard是否可用
     *
     * @return
     */
    public static boolean isSDCardEnable() {
        return Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
    }

    /**
     * 读取配置文件内容
     *
     * @return
     */
    public static Boolean initConfig() {
        String configMessage = FileUtils.txt2String(filePath);
        if (configMessage.equals("")) {
            Log.e("facesdk", "文件不存在");
            return false;
        }
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(configMessage);
            if (!identify(jsonObject)) {
                return false;
            }
            SingleBaseConfig.getBaseConfig().setCardType(jsonObject.getString("cardtype"));

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("facesdk", "文件内容异常,请检测是否规范");
            return false;
        }
    }

    // 校验sdcard里的txt文件内容是否正常
    public static boolean identify(JSONObject jsonObject) {
        try {
            Boolean display = (Boolean) jsonObject.get("display");
            Boolean isNirOrDepth = (Boolean) jsonObject.get("isNirOrDepth");

            Boolean debug = (Boolean) jsonObject.get("debug");
            int videoDirection = Integer.parseInt(jsonObject.getString("videoDirection"));
            if (!(videoDirection == 0 || videoDirection == 90 || videoDirection == 180 || videoDirection == 270)) {
                return false;
            }
            String detectFrame = (String) jsonObject.get("detectFrame");
            if (!(detectFrame.equals("wireframe") || detectFrame.equals("fixed_area"))) {
                return false;
            }

//            int radius = (int) jsonObject.get("radius");

            int detectDirection = (int) jsonObject.get("detectDirection");
            if (!(detectDirection == 0 || detectDirection == 90 || detectDirection == 180
                    || detectDirection == 270)) {
                return false;
            }

            String trackType = (String) jsonObject.get("trackType");
            if (!(trackType.equals("max") || trackType.equals("first") || trackType.equals("none"))) {
                return false;
            }

            int minimumFace = (int) jsonObject.get("minimumFace");
            if (minimumFace < 30) {
                return false;
            }

            float blur = Float.valueOf(jsonObject.get("blur") + "");
            if (blur > 1 || blur < 0) {
                return false;
            }

            int illumination = (int) jsonObject.get("illumination");
            if (illumination < 0 || illumination > 255) {
                return false;
            }

            float gesture = Float.valueOf(jsonObject.get("gesture") + "");

            float pitch = Float.valueOf(jsonObject.get("pitch") + "");
            if (pitch < -90 || pitch > 90) {
                return false;
            }

            float roll = Float.valueOf(jsonObject.get("roll") + "");
            if (roll < -90 || roll > 90) {
                return false;
            }

            float yaw = Float.valueOf(jsonObject.get("yaw") + "");
            if (yaw < -90 || yaw > 90) {
                return false;
            }

            float occlusion = Float.valueOf(jsonObject.get("occlusion") + "");
            if (occlusion < 0 || occlusion > 1) {
                return false;
            }


            float leftEye = Float.valueOf(jsonObject.get("leftEye") + "");
            if (leftEye < 0 || leftEye > 1) {
                return false;
            }

            float rightEye = Float.valueOf(jsonObject.get("rightEye") + "");
            if (rightEye < 0 || rightEye > 1) {
                return false;
            }

            float nose = Float.valueOf(jsonObject.get("nose") + "");
            if (nose < 0 || nose > 1) {
                return false;
            }

            float mouth = Float.valueOf(jsonObject.get("mouth") + "");
            if (mouth < 0 || mouth > 1) {
                return false;
            }

            float leftCheek = Float.valueOf(jsonObject.get("leftCheek") + "");
            if (leftCheek < 0 || leftCheek > 1) {
                return false;
            }

            float rightCheek = Float.valueOf(jsonObject.get("rightCheek") + "");
            if (rightCheek < 0 || rightCheek > 1) {
                return false;
            }

            float chinContour = Float.valueOf(jsonObject.get("chinContour") + "");
            if (chinContour < 0 || chinContour > 1) {
                return false;
            }

            float completeness = Float.valueOf(jsonObject.get("completeness") + "");
            if (completeness < 0 || completeness > 1) {
                return false;
            }

            int threshold = Integer.valueOf(jsonObject.get("threshold") + "");
            if (threshold < 0 || threshold > 100) {
                return false;
            }

            int activeModel = Integer.valueOf(jsonObject.get("activeModel") + "");
            if (!(activeModel == 1 || activeModel == 2)) {
                return false;
            }

            int timeLapse = Integer.valueOf(jsonObject.get("timeLapse") + "");

            int type = Integer.valueOf(jsonObject.get("type") + "");
            if (!(type == 1 || type == 2 || type == 3 || type == 4)) {
                return false;
            }

            float rgbLiveScore = Float.valueOf(jsonObject.get("rgbLiveScore") + "");
            if (rgbLiveScore < 0 || rgbLiveScore > 1) {
                return false;
            }

            float nirLiveScore = Float.valueOf(jsonObject.get("nirLiveScore") + "");
            if (nirLiveScore < 0 || nirLiveScore > 1) {
                return false;
            }

            float depthLiveScore = Float.valueOf(jsonObject.get("depthLiveScore") + "");
            if (depthLiveScore < 0 || depthLiveScore > 1) {
                return false;
            }
            int cameraType = jsonObject.getInt("cameraType");
            if (!(cameraType == 0 || cameraType == 1 || cameraType == 2 || cameraType == 3 ||
                    cameraType == 4 || cameraType == 5 || cameraType == 6)) {
                return false;
            }

            int mirrorRGB = jsonObject.getInt("mirrorRGB");
            if (!(mirrorRGB == 0 || mirrorRGB == 1)) {
                return false;
            }

            int mirrorNIR = jsonObject.getInt("mirrorNIR");
            if (!(mirrorNIR == 0 || mirrorNIR == 1)) {
                return false;
            }

            int rgbAndNirWidth = jsonObject.getInt("rgbAndNirWidth");
            int rgbAndNirHeight = jsonObject.getInt("rgbAndNirHeight");
            int depthWidth = jsonObject.getInt("depthWidth");
            int depthHeight = jsonObject.getInt("depthHeight");

        } catch (Exception e) {
            String errorMessage = getErrorInfoFromException(e);
            e.printStackTrace();
            Log.e("facesdk", "文件内容格式异常,请检测是否规范");
            return false;
        }

        return true;
    }

    /**
     * 修改配置文件内容并重新读取配置
     */
    public static void modityJson() {

        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("cardtype", SingleBaseConfig.getBaseConfig().getCardType());


            // 修改内容写入配置文件
            FileUtils.writeTxtFile(jsonObject.toString(), filePath);
            // 重新读取配置文件内容
            initConfig();

        } catch (Exception e) {

            e.printStackTrace();
        }

    }

    public static String getErrorInfoFromException(Exception e) {
        try {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            return "\r\n" + sw.toString() + "\r\n";
        } catch (Exception e2) {
            return "bad getErrorInfoFromException";
        }
    }

    /**
     * 判断数字正则表达式
     *
     * @param str
     * @return
     */
    public boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;

    }

    /**
     * 判断字符正则表达式
     *
     * @param str
     * @return
     */
    public boolean isString(String str) {

        return str.matches("[a-zA-Z]+");

    }
}
